package com.fit.dao.registration;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.LicencePlate;
import com.fit.entities.Registration;
import com.fit.entities.User;

public class RegistrationDAOImpl implements RegistrationDAO {

	@Inject
	private Session session;

	public boolean save(Registration registration) {
		if (registration != null) {
			session.save(registration);
			return true;
		}
		return false;
	}

	public List<Registration> findByLicencePlateNo(LicencePlate licencePlate) {
		List<Registration> list =  session.createCriteria(Registration.class).add(Restrictions.eq("licencePlate",licencePlate)).list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<Registration> findAll() {
		return session.createCriteria(Registration.class).list();
	}

	public boolean update(Registration registration) {
		if (registration != null) {
			session.update(registration);
			return true;
		}
		return false;
	}

	public Registration findByID(Long id) {
		List<Registration> list =  session.createCriteria(Registration.class).add(Restrictions.eq("id",id)).list();
		return list.get(0);
	}

	public Registration findLast(LicencePlate licencePlate) {
		List<Registration> list =  session.createCriteria(Registration.class).add(Restrictions.eq("licencePlate",licencePlate)).list();
		if(list.size()==1){
			return list.get(0);
		}
		Registration last = list.get(0);
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getDate().after(last.getDate())){
				last = list.get(i);
			}
		}
		return last;
	}

	public void delete(Long id) {
		Registration r = findByID(id);
		session.delete(r);
	}


}
